package controller

import (
	"github.com/labstack/echo"
	"net/http"
	"src/config"
	"src/controller/param"
	"src/model"
	"src/util/context"
	"strconv"
)

func Search(c echo.Context) error {
	GetParam := param.GetForumpost{}
	err := c.Bind(&GetParam)
	GetParam.Page, err = strconv.Atoi(c.QueryParam("page"))
	GetParam.PerPage, err = strconv.Atoi(c.QueryParam("per_page"))
	GetParam.Tags, err = strconv.Atoi(c.QueryParam("tags"))
	GetParam.Key = c.QueryParam("key")
	GetParam.T, err = strconv.Atoi(c.QueryParam("type"))
	if err != nil || GetParam.Page == 0 || GetParam.PerPage <= 0 {
		writeforumpostLoggerLoggerLog("Search", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	if GetParam.T < 1 {
		GetParam.T = 1
	}
	user_id := context.GetJWTUserOpenid(c)
	Forumpost, err := model.GetForumpost_score(GetParam.T, GetParam.Key, GetParam.Tags, 1, GetParam.Page*GetParam.PerPage, user_id)
	if err != nil {
		writeforumpostLoggerLoggerLog("Search", config.ErrorForumpostGetByType, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorForumpostGetByType)
	}
	Comment, err := model.GetCommentBykey_score(GetParam.Key, GetParam.Tags, 1, GetParam.Page*GetParam.PerPage, user_id)
	if err != nil {
		writeforumpostLoggerLoggerLog("Search", config.ErrorForumpostGetByType, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorForumpostGetByType)
	}
	i, j, num := 0, 0, 0
	for ; num < (GetParam.Page-1)*GetParam.PerPage && (i < len(Forumpost) || j < len(Comment)); num++ {
		if j >= len(Comment) || (i < len(Forumpost) && Forumpost[i].Score >= Comment[j].Score) {
			i++
		} else {
			j++
		}
	}
	var Data []model.ForumPost
	for num = 0; num < GetParam.PerPage && (i < len(Forumpost) || j < len(Comment)); num++ {
		if j >= len(Comment) || (i < len(Forumpost) && Forumpost[i].Score >= Comment[j].Score) {
			Data = append(Data, Forumpost[i])
			i++
		} else {
			data, _ := model.GetForumpostByid(Comment[j].ForumpostId, user_id)
			if data.Type < GetParam.T {
				num--
			} else {
				Data = append(Data, data)
			}
			j++
		}
	}
	resData := map[string]interface{}{}
	if len(Data) == 0 {
		resData["Forumpost"] = []model.ForumPost{}
	} else {
		resData["Forumpost"] = Data
	}
	return context.RetData(c, resData)
}
